#ifndef NETBAIDU
#define NETBAIDU

#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QScriptValue>
#include <QScriptEngine>
#include <QDataStream>
#include <QScriptValueIterator>
#include <QFile>
#include <QObject>
#include <QStandardPaths>
#include<QDebug>

#include <QJsonDocument>
#include <QJsonValue>
#include <QJsonArray>
#include <QJsonObject>

class NetBaidu:public  QObject
{
    Q_OBJECT
public:
    NetBaidu()
    {
        strText="";
        API_id="7782596";
        API_key="qaby0i9lhaBplZDZeyuZGHGs";
        API_secret_key="8QktsK3GIhj8KOQFsPR489CmC0Io5NB1";
        API_access_token="";//进入令牌
        API_language="zh";
        QString SP= QStandardPaths::standardLocations(QStandardPaths::GenericDataLocation).first();
        API_record_path=SP+"/source.pcm";//"/mnt/sdcard/Android/data/test.amr";//录音文件的路径
        flag=1;
         manager = new QNetworkAccessManager();
         connect(manager,SIGNAL(finished(QNetworkReply*)),this,SLOT(replyFinish(QNetworkReply*)));
         manager->get(QNetworkRequest(QUrl( "https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=GvZoZ651bHqvGXZISE1oyCFf&client_secret=12cac8c453b83e945a485a5fef8072a0")));

    }
    Q_INVOKABLE void getText(QString para_API_id, QString para_API_access_token,QString para_API_language, QString para_API_record_path)
    {
        QFile file(para_API_record_path);
        if( !(file.open(QIODevice::ReadOnly)))
        {
            qDebug()<<"没有文件";
            return;
        }

        QDataStream in(&file);//二进制数据
        m_buf =new char[file.size()];
        in.readRawData(m_buf,file.size());//从file中读取到char中
        file.close();

        QString  getTextUrl = "http://vop.baidu.com/server_api?lan=" + para_API_language + "&cuid=" + para_API_id + "&token=" + para_API_access_token;
        QUrl url;
        url.setUrl(getTextUrl);
        QNetworkRequest request(url);
        request.setHeader(QNetworkRequest::ContentTypeHeader, "audio/pcm;rate=16000");
        QByteArray arr = QByteArray(m_buf, file.size());
         manager->post(request,arr);
    }

    Q_INVOKABLE QString return_str()
    {
        return strText;
    }
    Q_INVOKABLE void set_path(QString path)
    {
        API_record_path=path;
    }

    Q_PROPERTY(QString str READ str  NOTIFY strtextchange )
    QString str()
    {
        return strText;
    }
signals:
    void strtextchange(QString str);
    void voiceRecognitionErro();
public slots:
     void set_gettext()
     {
        qDebug()<<"set_gettext()";
         getText(API_id,API_access_token,API_language,API_record_path);
     }
private slots:
    void replyFinish(QNetworkReply *reply)
    {
        if(flag==1)
        {
            QString strJsonAccess=reply->readAll();//获得http返回的信息
            qDebug()<<strJsonAccess;
            QScriptValue jsonAccess;//容器数据类型脚本
            QScriptEngine engineAccess;
            jsonAccess = engineAccess.evaluate("value = " + strJsonAccess);
            QScriptValueIterator iteratorAccess(jsonAccess);
            while (iteratorAccess.hasNext())
            {
                    iteratorAccess.next();
                  if(iteratorAccess.name()=="access_token")
                      API_access_token = iteratorAccess.value().toString();//得到 API_access_token,验证是百度用户
                  qDebug()<<"验证"<<API_access_token;
             }
            if(API_access_token=="")
            {
                return;
            }
            flag=0;
            reply->deleteLater();//释放
        }
        else
        {
            QByteArray readBuff= reply->readAll();
            QString strJsonText =readBuff;//对文本进行解析,,这个返回的JSON包所携带的是语音文本
    //        QString strText="";
            qDebug()<<"dasd"<<strJsonText;

            QJsonDocument jsDoc;
            QJsonParseError jsError;
            jsDoc=QJsonDocument::fromJson(readBuff,&jsError);//从文件中读取数据
                if(jsError.error==QJsonParseError::NoError)//判断文件是否为空
                {
                    QJsonObject tempJSObj=jsDoc.object();
                    int err_no=tempJSObj.value("err_no").toInt ();
                    if(err_no!=0) {
                        emit voiceRecognitionErro();
                    } else {
                        QJsonArray tempJSArray=tempJSObj.value ("result").toArray ();
                        if(tempJSArray.empty ()) {
                            emit voiceRecognitionErro ();
                        } else {
                            for(int i=0,stand=tempJSArray.count ();i<stand;i++) {
                                emit strtextchange(tempJSArray.at (i).toString ());
                            }
                        }
                    }
                }
                else
                {
                    emit voiceRecognitionErro();
                }




//            QScriptValue jsontext;
//            QScriptEngine engineText;
//            jsontext = engineText.evaluate("value = " + strJsonText );
//            QScriptValueIterator iteratorText(jsontext);
//            while (iteratorText.hasNext())
//            {
//                   iteratorText.next();
//                  if(iteratorText.name()=="result")
//                  {
//                      strText = iteratorText.value().toString();
//                      emit strtextchange(strText);
//                      break;
//                  }
//             }
        }
    }

private:
    QString strText;

    QNetworkAccessManager *manager;
    QNetworkRequest *req;
    QString API_access_token;
    QString API_id;
    QString API_key;
    QString API_secret_key;
    QString API_record_path;
    QString API_language;
    char * m_buf;
    int flag;
};

#endif // NETBAIDU

